import requests
from bs4 import BeautifulSoup

class China:
    # 获取首页板块内容
    def get_home_content(self, url):
        response = requests.get(url, timeout=10)
        response.encoding = response.apparent_encoding  # 自动检测编码
        soup = BeautifulSoup(response.text, 'html.parser')

        # content = soup.find('div', attrs={'id': 'scroll'})
        # content = soup.find('div', id='scroll')
        # prices = soup.find_all('p', class_='price') # 获取p标签下 class=price的所有元素

        scroll = soup.find('div', attrs={'id': 'scroll'})
        content = scroll.find_all('div', attrs={'class': 'box'})

        market_index = []  # 大盘指数
        for div in content:
            # 提取div内的所有p标签
            p_tags = div.find_all('p')  # [1,3](@ref)

            item = {
                "title": p_tags[0].get_text(strip=True),  # 第一个p标签内容
                "value": p_tags[1].get_text(strip=True),  # 第二个p标签内容
                "class": p_tags[2]['class'][0],  # 第二个p标签内容
                "number": (p_tags[2].find_all('font'))[0].get_text(strip=True),  # 涨跌数量
                "rate": (p_tags[2].find_all('font'))[1].get_text(strip=True),  # 涨跌比例
                "is_rise": 1 if p_tags[2]['class'][0] == 'r' else 0  # 判断涨跌
            }
            market_index.append(item)

        result = {
            'title': '股市行情',
            "market_index": market_index,
        }
        # print(result)
        return result
